package com.example.file_management.controller;

import com.example.file_management.pojo.material.Assessment;
import com.example.file_management.service.AssessmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/assessments")
@CrossOrigin(origins = "http://localhost:5173")
public class AssessmentController {

    private final AssessmentService assessmentService;

    @Autowired
    public AssessmentController(AssessmentService assessmentService) {
        this.assessmentService = assessmentService;
    }

    // 插入评估记录
    @PostMapping
    public ResponseEntity<Assessment> insertAssessment(@RequestBody Assessment assessment) {
        int result = assessmentService.insertAssessment(assessment);
        if (result > 0) {
            return ResponseEntity.ok(assessment);
        } else {
            return ResponseEntity.badRequest().build();
        }
    }

    // 根据任务ID查询评估记录
    @GetMapping("/task/{taskId}")
    public ResponseEntity<List<Assessment>> getAssessmentsByTaskId(@PathVariable int taskId) {
        List<Assessment> assessments = assessmentService.getAssessmentsByTaskId(taskId);
        if (assessments != null && !assessments.isEmpty()) {
            return ResponseEntity.ok(assessments);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 更新评估记录
    @PutMapping("/{assessmentId}")
    public ResponseEntity<Assessment> updateAssessment(@PathVariable Integer assessmentId, @RequestBody Assessment assessmentDetails) {
        Assessment assessment = (Assessment) assessmentService.getAssessmentsByTaskId(assessmentId);
        if (assessment != null) {
            assessment.setAssessmentName(assessmentDetails.getAssessmentName());
            assessment.setAssessmentCriteria(assessmentDetails.getAssessmentCriteria());
            assessment.setScore(assessmentDetails.getScore());
            assessment.setAssessmentDate(assessmentDetails.getAssessmentDate());
            assessment.setAssessor(assessmentDetails.getAssessor());
            int result = assessmentService.updateAssessment(assessment);
            if (result > 0) {
                return ResponseEntity.ok(assessment);
            } else {
                return ResponseEntity.badRequest().build();
            }
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 根据评估ID删除评估记录
    @DeleteMapping("/{assessmentId}")
    public ResponseEntity<Void> deleteAssessmentById(@PathVariable Integer assessmentId) {
        int result = assessmentService.deleteAssessmentById(assessmentId);
        if (result > 0) {
            return ResponseEntity.ok().build();
        } else {
            return ResponseEntity.notFound().build();
        }
    }
}